import api from '@/api'

const state = {
    account: localStorage.account === undefined ? {} : JSON.parse(localStorage.account) || {},
    token: localStorage.token || '',
    failure_time: localStorage.failure_time || '',
    permissions: localStorage.permissions === undefined ? [] : JSON.parse(localStorage.permissions) || []
}

const getters = {
    isLogin: state => {
        let retn = false
        if (state.token) {
            retn = true
        }
        return retn
    },
    isAdmin: state => {
        if (state.permissions !== undefined && state.permissions.length > 0) {
            return state.permissions[0].isAdmin
        }
        return false
    }
}

const actions = {
    login({commit}, data) {
        return new Promise((resolve, reject) => {
            // 通过 mock 进行登录
            api.post('mock/member/login', data).then(res => {
                // 判断是否admin权限 暂时写死
                res.data.permissions = [{isAdmin: true}]
                commit('setUserData', res.data)
                resolve()
            }).catch(error => {
                reject(error)
            })
        })
    },
    setUserInfo({commit}, data) {
        return new Promise((resolve, reject) => {
            commit('setUserData', data)
            resolve()
        })
    },
    logout({commit}) {
        return new Promise((resolve, reject) => {
            commit('removeUserData')
            resolve()
        })
    },
    // 获取我的权限
    getPermissions({state, commit}) {
        return new Promise(resolve => {
            // 通过 mock 获取权限
            api.get('mock/member/permission', {
                params: {
                    account: state.account
                }
            }).then(res => {
                commit('setPermissions', res.data.permissions)
                resolve(res.data.permissions)
            })
        })
    }
}

const mutations = {
    setUserData(state, data) {
        localStorage.setItem('account', JSON.stringify(data.account))
        localStorage.setItem('token', data.token)
        // localStorage.setItem('failure_time', data.failure_time)
        localStorage.setItem('permissions', JSON.stringify(data.permissions))
        state.account = data.account
        state.token = data.token
        state.failure_time = data.failure_time
        state.permissions = data.permissions
    },
    removeUserData(state) {
        console.log('ppppppppppppppppppppppppppppppppppp')
        localStorage.removeItem('account')
        localStorage.removeItem('token')
        localStorage.removeItem('failure_time')
        localStorage.removeItem('permissions')
        state.account = {}
        state.token = ''
        state.failure_time = ''
        state.permissions = []
    },
    setPermissions(state, permissions) {
        state.permissions = permissions
        // state.permissions = {isAdmin: true}
    }
}

export default {
    namespaced: true,
    state,
    actions,
    getters,
    mutations
}
